package ua.kharkov.khpi.tarasenko.bach.web.command.admin;

import java.sql.Connection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import ua.kharkov.khpi.tarasenko.bach.analysis.prefixspan.Node;
import ua.kharkov.khpi.tarasenko.bach.analysis.prefixspan.PseudoDbPS;
import ua.kharkov.khpi.tarasenko.bach.analysis.tnr.PseudoDbTNR;
import ua.kharkov.khpi.tarasenko.bach.analysis.utils.AnalysisUtils;
import ua.kharkov.khpi.tarasenko.bach.core.Constant;
import ua.kharkov.khpi.tarasenko.bach.core.EShopException;
import ua.kharkov.khpi.tarasenko.bach.core.db.ConnectionManager;
import ua.kharkov.khpi.tarasenko.bach.core.db.DBUtils;
import ua.kharkov.khpi.tarasenko.bach.core.logging.CustomerSession;
import ua.kharkov.khpi.tarasenko.bach.dao.core.DAOFactory;
import ua.kharkov.khpi.tarasenko.bach.dao.core.DAOFactory.DAO_TYPE;
import ua.kharkov.khpi.tarasenko.bach.dao.core.usersession.UserSessionDAO;
import ua.kharkov.khpi.tarasenko.bach.service.AnalysisService;
import ua.kharkov.khpi.tarasenko.bach.web.command.Command;

public class AnalyseCommand extends Command {
	private static final Logger LOG = Logger.getLogger(AnalyseCommand.class);

	private static final String ATTRIBUTE_ANALYSIS_TYPE = "analysis_type";
	private static final String ANALYSIS_TYPE_CART = "cart";
	private static final String ANALYSIS_TYPE_NAV = "nav";

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws EShopException {

		String forward = Constant.PAGE_RECOMMENDATIONS_SETTINGS;
		String[] actionsToPerform = request
				.getParameterValues(ATTRIBUTE_ANALYSIS_TYPE);

		String minSupString = request.getParameter("min_sup");
		double minSup = 0d;
		try {
			minSup = Double.parseDouble(minSupString);
		} catch (NumberFormatException ex) {
			LOG.debug("Min support is unparsable, min_sup=" + minSupString);
			return forward;
		}

		String minConfString = request.getParameter("min_conf");
		double minConf = 0d;
		try {
			minConf = Double.parseDouble(minConfString);
		} catch (NumberFormatException ex) {
			LOG.debug("Min confidence is unparsable, min_conf=" + minConfString);
			return forward;
		}

		String numOfRulesString = request.getParameter("rules_num");
		int numOfRules = 0;
		try {
			numOfRules = Integer.parseInt(numOfRulesString);
		} catch (NumberFormatException ex) {
			LOG.debug("Min confidence is unparsable, min_conf=" + minConfString);
			return forward;
		}

		if (actionsToPerform == null) {
			return forward;
		} else {
			Connection conn = null;
			try {
				conn = ConnectionManager.getConnection();
				UserSessionDAO userSessionDAO = DAOFactory.getDAOFactory(
						DAO_TYPE.MYSQL).getUserSessionDAO(conn);
				List<CustomerSession> sessions = userSessionDAO
						.getAllSessions();
				PseudoDbPS db = AnalysisUtils.transformToPseudoPsBd(sessions);
				AnalysisService service = new AnalysisService();
				for (String action : actionsToPerform) {
					if (action.equals(ANALYSIS_TYPE_CART)) {
						db = AnalysisUtils.getAccessDB(db);
						Node rootNode = service.doNavigationRecsAnalysis(db, minSup);
						
						//Put new tree into app context
						request.getServletContext().setAttribute(Constant.CONTEXT_ATTRIBUTE_TREE, rootNode);
					} else if (action.equals(ANALYSIS_TYPE_NAV)) {
						db = AnalysisUtils.getBoughtItemSets(db);
						PseudoDbTNR dbTnr = AnalysisUtils
								.transformPSToTRNDb(db);
						service.doCartRecsAnalysis(dbTnr, minConf, numOfRules);
					}
				}
			} catch (EShopException e) {
				DBUtils.close(conn);
				throw e;
			} finally {
				if (conn != null) {
					DBUtils.close(conn);
				}
			}
		}
		return forward;
	}
}
